package com.gameco.data.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import core.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import util.SM2EncryptionUtil;
import vo.DataRoot;
import vo.v1.DataRoot_V1;
import vo.v2.DataRoot_V2;

import java.util.HashMap;
import java.util.Map;

/**
 * 维修控制类
 */
@RestController
@RequestMapping("/data")
@Slf4j
public class EncryptionController {

    @Autowired
    private RestTemplate restTemplate; // 注入 RestTemplate

    // 从配置文件中获取公钥，默认值为"xxx"
    @Value("${spring.publicKey:xxx}")
    private String publicKey;

    /**
     * 维修服务对前端入参进行公钥加密处理
     * @param root 传输对象
     * @return piResponse
     */
    @PostMapping("/encrypt")
    public ApiResponse<String> encrypt(@RequestBody DataRoot root)  {
        try {
            // 创建 ObjectMapper 并启用字段排序
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
            String jsonData = null;
            if(root.getCodeVersion().equals("0.1")){
                DataRoot_V1 root_v1 = objectMapper.convertValue(root, DataRoot_V1.class);
                // 将对象转换为 JSON 字符串
                jsonData = objectMapper.writeValueAsString(root_v1);
            }
            if(root.getCodeVersion().equals("0.2")){
                DataRoot_V2 root_v2 = objectMapper.convertValue(root, DataRoot_V2.class);
                // 将对象转换为 JSON 字符串
                jsonData = objectMapper.writeValueAsString(root_v2);
            }
            log.info("公钥 {}" , publicKey);
            // 调用 SM2EncryptionUtil 工具类的 encrypt 方法，使用生成的公钥对传入的 JSON 数据进行加密
            String xmlEncryptionData = SM2EncryptionUtil.encrypt(publicKey,jsonData, root.getCodeVersion());
            log.info("客户端生成加密数据 {}",xmlEncryptionData);
            // 调用 callServiceAnalysis 方法模拟 HTTP 调用服务端接口，传入加密后的 JSON 数据和私钥
            return  callServiceAnalysis(xmlEncryptionData);
        }catch (Exception e){
            log.info("文件加密失败 {}",e.getMessage());
            return ApiResponse.fail("加密失败: " + e.getMessage());
        }
    }

    /**
     * 模拟调用 航司服务接口
     * @param xmlEncryptionData
     * @return
     */
    public ApiResponse<String> callServiceAnalysis(String xmlEncryptionData) {
        // 目标服务的 URL
        String url = "http://localhost:19009/platform/decryptData";
//        String url = "http://8.134.77.199:10881/platform/decryptData";
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 构造请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("xmlEncryptionData", xmlEncryptionData);
        // 构造请求实体（包含请求头和请求体）
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
        // 发起 POST 请求
        ResponseEntity<ApiResponse> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                ApiResponse.class
        );
        // 返回响应结果
        return responseEntity.getBody();
    }
}